package com.simple.gateway.core.network;

import com.simple.gateway.core.session.Configuration;
import com.simple.gateway.core.session.defaults.DefaultGatewaySessionFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.Callable;

/**
 * 项目: simple-gateway-core
 * <p>
 * 功能描述: 会话服务器
 *
 * @author: WuChengXing
 * @create: 2023-08-02 11:04
 **/
public class GatewaySocketServer implements Callable<Channel> {

    private final Logger logger = LoggerFactory.getLogger(GatewaySocketServer.class);

    private final DefaultGatewaySessionFactory gatewaySessionFactory;
    private final Configuration configuration;


    private final EventLoopGroup boss;
    private final EventLoopGroup work;
    private Channel channel;

    public GatewaySocketServer(Configuration configuration, DefaultGatewaySessionFactory gatewaySessionFactory) {
        this.configuration = configuration;
        this.gatewaySessionFactory = gatewaySessionFactory;
        boss = new NioEventLoopGroup(configuration.getBossNThreads());
        work = new NioEventLoopGroup(configuration.getWorkNThreads());
    }

    @Override
    public Channel call() throws Exception {
        ChannelFuture channelFuture = null;
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(boss, work)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new GatewayChannelInitializer(configuration, gatewaySessionFactory));

            channelFuture = b.bind(new InetSocketAddress(configuration.getPort())).syncUninterruptibly();
            this.channel = channelFuture.channel();
        } catch (Exception e) {
            logger.error("socket server start error.", e);
        } finally {
            if (null != channelFuture && channelFuture.isSuccess()) {
                Channel channel = channelFuture.channel();
                InetSocketAddress localSocketAddress = (InetSocketAddress) channel.localAddress();
                logger.info("socket server start done; LOCAL ==> 地址：[{}]，端口：[{}]", localSocketAddress.getHostName(), localSocketAddress.getPort());
            } else {
                logger.error("socket server start error.");
            }
        }
        return channel;
    }
}
